<template>
  <div class="tw-datasetchart" ref="chart" :style="{height: height, width: width, backgroundColor: bgColor}">
    <div style="position:relative;width:100%;height:100%">
        <div class="m-school-map" id="map" ref="scatterMap" :style="{height: height, width: width, backgroundColor: bgColor}"></div>
        <div style="position: absolute;top:0;left:0;" :style="{height: height, width: width, backgroundColor: bgColor}" v-if="maphidden!=='transparent'">
        </div>
        <div style="position: absolute;top: 20px;right: 20px;cursor: pointer;padding: 2px 8px;border: 1px solid #0469f1;z-index:9;border-radius: 5px;color: #00a7fe;" @click="backtop" v-if="parseInt(this.areaId) !== curAreaId">返回上一级</div>
    </div>
  </div>
</template>

<script>
import props from './props'
import AMapLoader from '@amap/amap-jsapi-loader'
let map = null
let myChart = null

export default {
  name: 'chart-map-echart',

  props,

  data() {
    return {
      maphidden: 'transparent',
      parentJson: null,
      parentInfo: [],
      pointSimplifierIns: null,
      districtExplorer: null,
      curAreaId: parseInt(this.areaId),
      parentAreaId: parseInt(this.areaId),
      jsonlength: 0
    }
  },

  computed: {

  },

  methods: {
    searchCity (adcode) {
      let vm = this
      vm.maphidden = vm.bgColor
      if (this.myChart) {
        this.myChart.dispose()
      }
      if (this.map) {
        this.map.destroy()
        this.map = null
      }
      if (adcode === parseInt(this.areaId)) { // 最顶部清空
        this.curAreaId = parseInt(this.areaId)
        this.parentInfo = []
      }
      AMapLoader.load({
        'key': vm.mapKey,   // 申请好的Web端开发者Key，首次调用 load 时必填
        'version': '1.4.15',   // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        'plugins': vm.mapPlugins ? vm.mapPlugins.split(',') : [],  // 插件列表
        'AMapUI': {             // 是否加载 AMapUI，缺省不加载
          'version': '1.1',   // AMapUI 缺省 1.1
          'plugins':vm.mapUIPlugins ? vm.mapUIPlugins.split(',') : [],       // 需要加载的 AMapUI ui插件
        },
        'Loca':{                // 是否加载 Loca， 缺省不加载
          'version': '1.3.2'  // Loca 版本，缺省 1.3.2
        }
      }).then((AMap)=>{
        vm.map = new AMap.Map('map', {
          resizeEnable: false,
          mapStyle: vm.mapStyle,
          center: vm.mapCenter ? vm.mapCenter.split(',') : [116.30946, 39.937629],
          zoom: parseFloat(vm.mapZoom)
        })

        let districtExplorer = new AMapUI.DistrictExplorer({
          eventSupport: true, // 打开事件支持
          zIndex: 100,
          map: vm.map
        })
        vm.districtExplorer = districtExplorer

        vm.loadAreaNode(adcode, districtExplorer)

        // districtExplorer.on('outsideClick', function(e) {
        //   console.log('outsideClick', e)
        //   districtExplorer.locatePosition(e.originalEvent.lnglat, function(error, routeFeatures) {
        //     // console.log('routeFeatures', routeFeatures)
        //     // if (vm.curAreaId !== parseInt(this.areaId)) {
        //     //   vm.loadAreaNode(parseInt(this.areaId), districtExplorer)
        //     //   vm.getXXSData()
        //     // }
        //   }, {
        //     levelLimit: 2
        //   })
        // })


        let pointSimplifierIns = new AMapUI.PointSimplifier({
          map: vm.map, //所属的地图实例
          autoSetFitView: false, //禁止自动更新地图视野
          zIndex: 200,
          getPosition: function(item) {
            if (!item) {
              return null
            }
            //返回经纬度
            return item.value
          },
          getHoverTitle: function(dataItem, idx) {
            return dataItem.name
          },
          renderOptions: {
            //点的样式
            pointStyle: {
              width: parseInt(vm.pointRadius),
              height: parseInt(vm.pointRadius),
              fillStyle: vm.pointColor
            },
            //鼠标hover时的title信息
            hoverTitleStyle: {
              position: 'top'
            }
          }
        })
        vm.pointSimplifierIns = pointSimplifierIns

        // vm.map.off('click')
        // vm.map.on('click', function(ev) {
        //   console.log('click', ev.originEvent)
        //   // ev.domEvent.stopPropagation()
        // })

        if (!vm.useEchart) {
          vm.map.on("complete", function () {
            vm.maphidden = 'transparent'
            if (vm.data.length > 0) {
              pointSimplifierIns.setData(vm.data)
            }
          })
        }

        if (vm.useClick) {
          pointSimplifierIns.on('pointClick', function (e, p) {
            // console.log('e')
            // if (vm.jsonlength === 0) {
              // console.log('aaaaa', vm.jsonlength)
            let v = ['', p.data.name]
            vm.$emit('input', v)
            vm.$emit('change', v)
            // }
          })
        }

        if (vm.useDrilldown) {
          districtExplorer.on('featureClick', function(e, feature) {
            // console.log('f')
            let props = feature.properties
            // 如果存在子节点
            if (vm.curAreaId !== props.adcode) {
              // 切换聚焦区域
              vm.loadAreaNode(props.adcode, districtExplorer)
              // if (vm.curAreaId !== parseInt(vm.areaId)) {
              let v = [vm.curAreaId, '']
              vm.$emit('input', v)
              vm.$emit('change', v)
              // }
            }
          })
        }
      }).catch(e => {
        console.log(e)
      })
    },
    loadAreaNode (adcode, districtExplorer) {
      let vm = this
      let colors = vm.colors
      vm.curAreaId = adcode

      districtExplorer.loadAreaNode(adcode, (error, areaNode) => {
        if (error) {
          console.error(error)
          return
        }
        let Json = areaNode.getSubFeatures()
        vm.jsonlength = Json.length
        let aProps = areaNode.getProps()
        // console.log('aProps', aProps)
        vm.parentAreaId = aProps.acroutes && aProps.acroutes.length > 0 ? aProps.acroutes[aProps.acroutes.length - 1] : parseInt(vm.areaId)

        if (vm.useEchart) {
          // 这里判断一下
          // let Json = areaNode.getSubFeatures()
          let plength = vm.parentInfo.length
          // 在同级上下钻再返回再下钻继续返回，应该只添加一个父级
          if (Json.length > 0 && !(plength > 0 && vm.parentInfo[plength - 1].cityCode === adcode)) {
            vm.parentInfo.push({
              cityCode: adcode,
              level: Json[0].properties.level // province, city, district
            })
          }

          // 说明当前是市级别了,将这个值存起来
          if (Json.length > 0 && Json[0].properties.level == 'district') {
            vm.parentJson = Json
          } else if (Json.length === 0) { // 说明当前是县级
            if (vm.parentJson === null) {
              return
            } else if (vm.parentJson.length === 0) {
              return
            }
            Json = vm.parentJson.filter(item => {
              if (item.properties.adcode === adcode) {
                return item
              }
            })
            if (Json.length === 0) return
          }

          // 获取地图数据
          vm.getMapData(Json)
        } else {
          //更新地图视野
          if (vm.autoDebouns) {
            vm.map.setBounds(areaNode.getBounds(), null, null, true)
          } else {
            vm.map.setZoomAndCenter(parseFloat(vm.zoom), aProps.center)
          }
          //清除已有的绘制内容
          districtExplorer.clearFeaturePolygons()

          //绘制子区域
          if (Json.length > 0) {
            districtExplorer.renderSubFeatures(areaNode, function(feature, i) {
              let fillColor = colors[i % colors.length]

              return {
                cursor: 'default',
                bubble: true,
                strokeColor: vm.borderColor, //线颜色
                strokeOpacity: 1, //线透明度
                strokeWeight: 1, //线宽
                fillColor: fillColor, //填充色
                fillOpacity: 1, //填充透明度
              }
            })

            districtExplorer.renderParentFeature(areaNode, {
              cursor: 'default',
              bubble: true,
              strokeColor: vm.borderColor, //线颜色
              strokeOpacity: 1, //线透明度
              strokeWeight: 1, //线宽
              fillColor: vm.curAreaId === parseInt(vm.areaId) ? null : vm.areaColor, //填充色
              fillOpacity: 1, //填充透明度
            })
          } else {
            //绘制父区域
            districtExplorer.renderParentFeature(areaNode, {
              cursor: 'default',
              bubble: true,
              strokeColor: vm.borderColor, //线颜色
              strokeOpacity: 1, //线透明度
              strokeWeight: 1, //线宽
              fillColor: vm.areaColor, //填充色
              fillOpacity: 1, //填充透明度
            })
          }
          districtExplorer.setAreaNodesForLocating([areaNode])

          // if (vm.pointSimplifierIns) {
          //   vm.setNewMapData()
          // }
        }
      })
    },
    getMapData (Json) {
      if (this.useEchart) {
        this.maphidden = this.bgColor
        // 这里我们模拟数据进行数据获取
        // 实际项目中会调接口把坐标和值返回来
        // 必须将数据写成数组对象格式,name,value是必须参数，后面的根据自己实际情况自定义添加
        // 除了name和value,其他的名字可以随便取
        // 分布图不需要坐标就可以实现，只需要名字和地图行政区的名字对应上了就行
        let mapData = Json.map(item => {
          return ({
            name: item.properties.name,
            value: Math.random() * 1000,
            level: item.properties.level,
            cityCode: item.properties.adcode
          })
        })

        let scatterData = this.data

        let mapJson = {}
        // geoJson必须这种格式
        mapJson.features = Json
        this.initEchartsMap(scatterData, mapData, mapJson)
      } else {
        if (this.pointSimplifierIns) {
          this.pointSimplifierIns.setData(vm.data)
        }
      }
    },
    initEchartsMap (scatterData, mapData, mapJson) {
      let vm = this
      this.myChart = window.echarts.init(this.$refs.scatterMap)
      // 注册地图,前面名字自定义,后面是高德获取的geoJson
      window.echarts.registerMap('Map', mapJson)
      //这里要加true表示重新绘制,不然下钻或筛选后,地图会飞出去
      this.myChart.setOption({
        // backgroundColor: vm.bgColor,
        tooltip: {
          trigger: "item",
          formatter: p => {
            // let val = p.value;
            // if (window.isNaN(val)) {
            //   val = 0
            // }
            // let txtCon = "<div style='text-align:center'>" + p.name + ":<br />数据：" + val.toFixed(2) + '</div>'
            let txtCon = "<div style='text-align:center'>" + p.name + '</div>'
            return txtCon
          }
        },
        geo: {
          map: 'Map',
          roam: true,
          zoom: 1.1,
          // left: '150',
          itemStyle: { //地图区域的多边形 图形样式
            // color: 'rgba(209,250,12,0.5)',
            normal: { //是图形在默认状态下的样式
              color: vm.areaColor, // 'rgba(37,124,169)',
              label: {
                show: true, //是否显示标签
                textStyle: {
                  color: '#fff' // 'rgb(249, 249, 249)'
                },
              },

              borderWidth: 1,
              borderColor: vm.borderColor, // 'rgba(37,124,169)',
              // areaColor: 'rgba(37,124,169)',
              shadowColor: '#657df5', // 'rgba(37,124,169)',
              // shadowOffsetY: 15,
              // shadowOffsetX: 8,
              shadowBlur: 3,
            },
          },
          label: {
            show: true,
            textStyle: {
              color: '#fff', // "rgb(249, 249, 249)", // 省份标签字体颜色
              // position: 'top',
              fontSize: 16
            }
          },
          emphasis: {
            itemStyle: {
              color: vm.areaHoverColor
            },
            label: {
              show: true,
              color: '#fff'
            }
          }
        },

        series: [
          {
            name: '散点',
            type: 'effectScatter',
            coordinateSystem: 'geo',
            data: scatterData,
            showEffectOn: 'emphasis',
            effectType: '',
            animation: false,
            rippleEffect: {
              brushType: 'stroke'
            },
            hoverAnimation: true,
            zlevel: 1,
            symbolSize: function(val) {
              return vm.pointRadius
            },
            tooltip: {
              position: 'top',
            },
            label: {
              normal: {
                formatter: '{b}',
                position: 'right',
                show: false
              },
              emphasis: {
                show: false
              }
            },
            itemStyle: {
              normal: {
                color: vm.pointColor
              }
            }
        },
        {
          name: "地图",
          type: "map",
          geoIndex: 0,
          map: "Map",
          data: mapData
        }]
      }, true)

      vm.maphidden = 'transparent'

      // 点击前解绑，防止点击事件触发多次
      this.myChart.off('click')
      this.myChart.on('click', this.clickMap)
    },
    // 这里有个参数，就是点击的那个地块的数据信息
    clickMap (params) {
      // 如果当前是最后一级，那就直接return
      if (params.componentType === 'geo') { // 选中区域

      } else if (params.componentType === 'series') {
        if (!this.useDrilldown) {
          return
        }
        if (params.componentSubType === 'map') { // 选中区域
          let data = params.data
          if (data.level === 'district') {
            if (this.curAreaId !== data.cityCode) {
              this.curAreaId = data.cityCode
              let Json = this.parentJson.filter(item => {
                if (item.properties.adcode === data.cityCode) {
                  return item
                }
              })
              this.getMapData(Json)
            }

            if (this.parentInfo.length > 0 && this.parentInfo[this.parentInfo.length - 1].level === 'district') {
              this.parentInfo.push({
                cityCode: data.cityCode,
                level: 'xiangzhen'
              })
            }

          } else {
            this.curAreaId = data.cityCode
            this.loadAreaNode(data.cityCode, this.districtExplorer)
          }

          let v = [this.curAreaId, '']
          this.$emit('input', v)
          this.$emit('change', v)
        } else if (params.componentSubType === 'effectScatter') { // 选中学校
          if (!this.useClick) {
            return
          }
          let v = ['', params.data.name]
          this.$emit('input', v)
          this.$emit('change', v)
        }
      }
    },
    backtop () {
      if (this.useEchart) {
        if (this.parentInfo.length > 1) {
          let data = this.parentInfo.pop()
          this.curAreaId = this.parentInfo[this.parentInfo.length - 1].cityCode
          if (data.level === 'xiangzhen') {
            this.getMapData(this.parentJson)
          } else {
            this.loadAreaNode(this.curAreaId, this.districtExplorer)
          }
        } else {
          this.loadAreaNode(parseInt(this.areaId), this.districtExplorer)
        }
      } else {
        this.loadAreaNode(this.parentAreaId, this.districtExplorer)
      }

      let v = [this.curAreaId, '']
      this.$emit('input', v)
      this.$emit('change', v)
    }
  },

  mounted () {
    this.searchCity(parseInt(this.areaId))

    // window.addEventListener('resize', this.resize)
  },

  beforeDestroy () {
    // window.removeEventListener('resize', this.resize)
    if (this.myChart) {
      this.myChart.dispose()
    }
    if (this.map) {
      this.map.destroy()
      this.map = null
    }
  },

  watch: {
    areaId () {
      this.searchCity(parseInt(this.areaId))
    },

    data: {
      deep: true,
      handler () {
        if (this.map && this.data.length > 0) {
          if (this.useEchart) {
            let Json = this.parentJson.filter(item => {
              if (item.properties.adcode === this.curAreaId) {
                return item
              }
            })
            this.getMapData(Json)
          } else {
            this.getMapData()
          }
        } else {
          this.searchCity(parseInt(this.areaId))
        }
      }
    },

    // option: {
    //   deep: true,
    //   handler () {
    //     this.setOption()
    //   }
    // }
  }
}
</script>

<style lang="scss">
  @import './css/index.scss';
</style>
